package com.share.device.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.share.common.core.exception.ServiceException;
import com.share.device.service.IMapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements IMapService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tencent.map.key}")
    private String key;

    @Override
    public JSONObject calculateLatLng(String keyword) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?address={address}&key={key}";

        Map<String, String> map = new HashMap<>();
        map.put("address", keyword);
        map.put("key", key);

        JSONObject response = restTemplate.getForObject(url, JSONObject.class, map);
        if (response.getIntValue("status") != 0) {
            throw new ServiceException("地图解析异常");
        }

        //返回第一条最佳线路
        JSONObject result = response.getJSONObject("result");
        System.out.println(result.toJSONString());
        return result.getJSONObject("location");
    }


    @Override
    public Double calculateDistance(String startLongitude, String startLatitude
            , String endLongitude, String endLatitude) {
      /*  try {
            // 参数校验
            if (startLongitude == null || startLatitude == null || endLongitude == null || endLatitude == null) {
                log.error("坐标参数为空");
                throw new ServiceException("坐标参数为空");
            }

            // 构建请求参数
            String from = startLatitude + "," + startLongitude;
            String to = endLatitude + "," + endLongitude;
            String url = "https://apis.map.qq.com/ws/direction/v1/walking/?from={from}&to={to}&key={key}";

            // 发送请求
            JSONObject result;
            try {
                result = restTemplate.getForObject(url, JSONObject.class, from, to, key);
            } catch (HttpClientErrorException e) {
                log.error("HTTP请求失败，状态码：{}", e.getStatusCode());
                throw new ServiceException("地图服务请求失败");
            } catch (Exception e) {
                log.error("地图服务调用异常：{}", e.getMessage(), e);
                throw new ServiceException("地图服务调用失败");
            }

            // 结果校验
            if (result == null) {
                log.error("地图服务返回空结果");
                throw new ServiceException("地图服务返回空结果");
            }

            int status = result.getIntValue("status");
            if (status != 0) {
                String message = result.getString("message");
                log.error("地图服务返回错误：{}", message);
                throw new ServiceException("地图服务错误：" + message);
            }

            // 解析结果
            try {
                JSONObject routes = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
                return routes.getBigDecimal("distance").doubleValue();
            } catch (Exception e) {
                log.error("结果解析失败：{}", e.getMessage(), e);
                throw new ServiceException("结果解析失败");
            }

        } catch (ServiceException e) {
            throw e; // 重新抛出业务异常
        } catch (Exception e) {
            log.error("计算距离时发生未知异常：{}", e.getMessage(), e);
            throw new ServiceException("计算距离失败");
        }*/
        Random random = new Random();
        BigDecimal randomDouble = BigDecimal.valueOf(random.nextDouble(100));

// 保留两位小数，并进行四舍五入
        BigDecimal roundedValue = randomDouble.setScale(1, RoundingMode.HALF_UP);
        double roundedDoubleValue = roundedValue.doubleValue();
        return roundedDoubleValue;
    }
}